package com.ddyx.service.product.app.system.controller;

import com.ddyx.common.base.controller.BaseController;
import com.ddyx.service.user.api.feign.RemoteUserClient;
import com.ddyx.service.user.api.vo.UserInfo;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.validation.constraints.NotNull;

/**
 * <p>
 *      调用远程服务demo  熔断保护
 * </p>
 * class: DemoController.java
 * author: agula
 * since: 2019-08-01  16:11
 */
@Slf4j
@DefaultProperties(defaultFallback = "defaultFallback") //设置默认服务熔断保护方法
@RestController
public class DemoController extends BaseController {

    /**
     * 实现远程调用方式1 RestTemplate对象
     */
    @Autowired
    RestTemplate restTemplate;

    /**
     * 实现远程调用方式2 远程服务接口
     */
    @Autowired
    private RemoteUserClient remoteUserClient;//远程用户调用接口

    @RequestMapping(value = "/getList", method = RequestMethod.GET)
    public Object getList(@NotNull @PathVariable Integer userId) {

        UserInfo userInfo = remoteUserClient.userInfo(userId);
        log.info(userInfo.toString());

        return successResult(userInfo);
    }

    /*针对单一接口做独立的熔断保护*/
    @HystrixCommand(fallbackMethod = "getUserListFallback")
    @GetMapping(value = "/getUserList")
    public Object getUserList() {

        UserInfo userInfo = restTemplate.getForObject("http://localhost:9001/user/api/user/getList", UserInfo.class);
        log.info(userInfo.toString());

        return successResult(userInfo);
    }

    /**
     * 针对单一接口做独立的熔断保护
     * author: agula
     * since: 2019-08-02
     */
    private String getUserListFallback() {
        return "查询用户列表服务较慢，请稍后再试。";
    }

    /**
     * 默认服务熔断保护方法
     * author: agula
     * since: 2019-08-02
     */
    private String defaultFallback() {
        return "查询服务较慢，请稍后再试。";
    }

}
